<script setup lang="ts">
defineOptions({
  name: "GAS_OPERATION_DETECTORMANAGE_ISOLATE_EDIT"
});
import { ref, reactive, computed, onMounted, nextTick, h, provide, inject } from "vue";
import {
  queryDetectorIsolateDetail,
  executeDetectorIsolate,
  confirmDetectorIsolate,
  returnDetectorIsolate,
  noticeReDetectorIsolate,
  queryReminderContent
} from "@/api/modules/operation";
import { queryFileList } from "@/api/modules/fab";
import { useRoute, useRouter } from "vue-router";
import { ArrowLeft } from "@px-ui/icons-vue";
import { PxScrollbar, PxMessage, PxMessageBox } from "px-ui";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import ReTeleport from "@/components/ReTeleport";
import baseInfoTable from "./components/baseInfoTable.vue";
import FileUpload from "@/components/Upload/FileUpload.vue";
import commonTable from "@/views/common/components/commonTable/index.vue";
import isolateDialog from "./components/isolateDialog.vue";

const route = useRoute();
const router = useRouter();

const appMainScrollbarRef = inject("appMainScrollbarRef", ref<InstanceType<typeof PxScrollbar>>());

const detectorIsolateRef = ref<HTMLElement | null>(null);
const detailData = ref<Record<string, any>>({});
provide("detailData", detailData);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const loading = ref<boolean>(false);

//  图片上传类型add：新增，edit：编辑，view：查看
// 基础信息
const uploadType = ref<string>("view");
const fileList = ref<Array<any>>([]);

// 隔离
// 隔离
// 隔离
const isShowIsolateData = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  //  待执行：1，4   待确认：2，5   待解隔离通知：3
  const {
    query: { status = "", type = "" }
  } = route;
  if (type === "check") {
    return Number(status) > 1;
  } else {
    return true;
  }
});
const uploadType_2 = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  //  待执行：1，4   待确认：2，5   待解隔离通知：3
  const {
    query: { status = "", type = "" }
  } = route;
  if (type === "check") {
    return "view";
  } else {
    return status === "1" ? "edit" : "view";
  }
});
const fileList_2 = ref<Array<any>>([]);
const form = reactive<{ fileIds: Array<any>; executeRemark: string }>({ fileIds: [], executeRemark: "" });

const changeFileListHandler = (fl: Array<any>) => {
  form.fileIds = [];
  if (!fl?.length) return;
  form.fileIds = fl.map(item => item.id);
};

// 解隔离
// 解隔离
// 解隔离
const isShowReIsolateData = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  //  待执行：1，4   待确认：2，5   待解隔离通知：3
  const {
    query: { status = "", type = "" }
  } = route;
  if (type === "check") {
    return Number(status) > 4;
  } else {
    return Number(status) > 3;
  }
});

const isShowIsolateBtn = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  //  待执行：1，4   待确认：2，5   待解隔离通知：3
  const {
    query: { status = "", type = "" }
  } = route;
  return type !== "check";
});

const isolateDisabled = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  //  待执行：1，4   待确认：2，5   待解隔离通知：3
  const {
    query: { status = "", type = "" }
  } = route;
  return Number(status) > 3;
});

const isolateDialogVisiable = ref<boolean>(false);
const isolateDialogType = ref<0 | 1>(0);

const isShowReIsolateReportData = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  const {
    query: { status = "" }
  } = route;
  return detailData.value?.taskType === "SIGN" && Number(status) > 4;
});

const uploadType_3 = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  //  待执行：1，4   待确认：2，5   待解隔离通知：3
  const {
    query: { status = "", type = "" }
  } = route;
  if (type === "check") {
    return "view";
  } else {
    return status === "4" ? "edit" : "view";
  }
});

const uploadType_4 = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  const {
    query: { status = "", type = "" }
  } = route;
  return type === "edit" && status === "5" ? "edit" : "view";
});

const fileList_3 = ref<Array<any>>([]);
const fileList_4 = ref<Array<any>>([]);
const fileIds_4 = ref<Array<any>>([]);

const form_2 = reactive<{ fileIds: Array<any>; executeRemark: string }>({ fileIds: [], executeRemark: "" });

const changeFileListHandler_2 = (fl: Array<any>) => {
  form_2.fileIds = [];
  if (!fl?.length) return;
  form_2.fileIds = fl.map(item => item.id);
};

const changeFileListHandler_3 = (fl: Array<any>) => {
  fileIds_4.value = [];
  if (!fl?.length) return;
  fileIds_4.value = fl.map(item => item.id);
};

const tableCloumns: Array<CommonTable.TableCloumnsType> = [
  {
    label: "侦测器",
    prop: "detectorCode",
    width: 200
  },
  {
    label: "气体类型",
    prop: "gasName",
    width: 200
  },
  {
    label: "位置",
    prop: "location",
    width: 200
  },
  {
    label: "备注",
    prop: "remark",
    width: 300
  }
];

const isShowSubmit = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  // 执行 1      确认 2     解隔离通知 3
  const {
    query: { type = "edit", c = "1" }
  } = route;
  if (type === "edit") {
    return c === "1";
  }
  return false;
});

const isShowConfirm = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  // 执行 1      确认 2     解隔离通知 3
  const {
    query: { type = "edit", c = "1" }
  } = route;
  if (type === "edit") {
    return c === "2";
  }
  return false;
});

const isShowNotive = computed(() => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  // 执行 1      确认 2     解隔离通知 3
  const {
    query: { type = "edit", c = "1" }
  } = route;
  if (type === "edit") {
    return c === "3";
  }
  return false;
});

const queryFileListFn = async (ids: Array<any>): Promise<Array<any>> => {
  if (!ids?.length) return [];
  const params = { ids };
  const res = await queryFileList(params);
  if (!res?.length) return [];
  return res;
};

const cancelHandler = () => {
  const path = "/gas/operation/detectorManage/isolate";
  router.push({ path });
};

const submitHandler = useThrottleFn(async () => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  //  待执行：1，4   待确认：2，5   待解隔离通知：3
  const {
    query: { status = "" }
  } = route;
  const msg = `确定完成${status === "1" ? "隔离" : "解隔离"}执行吗？`;
  PxMessageBox.confirm(msg, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const {
      query: { id = "" }
    } = route;
    if (!id) return;
    let params = {};
    if (status === "1") {
      const { fileIds = [], executeRemark = "" } = form;
      params = { id, fileIds, executeRemark };
    } else {
      const { fileIds = [], executeRemark = "" } = form_2;
      params = { id, fileIds, executeRemark };
    }
    loading.value = true;
    const res = await executeDetectorIsolate(params, () => {
      loading.value = false;
    });
    loading.value = false;
    PxMessage.success("提交成功！");
    cancelHandler();
  });
}, delay);

const sendBackHandler = useThrottleFn(async () => {
  PxMessageBox.confirm("确定退回隔离工单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const {
      query: { id = "" }
    } = route;
    if (!id) return;
    loading.value = true;
    const res = await returnDetectorIsolate(id as string, () => {
      loading.value = false;
    });
    loading.value = false;
    PxMessage.success("退回成功！");
    cancelHandler();
  });
}, delay);

const confirmHandler = useThrottleFn(async () => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  const {
    query: { id = "", status = "" }
  } = route;
  if (status === "5" && detailData.value?.taskType === "SIGN") {
    if (!fileIds_4.value?.length) {
      appMainScrollbarRef.value!.setScrollTop(1500);
      return PxMessage.error("请上传报告！");
    }
  }
  PxMessageBox.confirm("确定已审核侦测器隔离状态吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    if (!id) return;
    const params = { id };
    if (status === "5" && detailData.value?.taskType === "SIGN") {
      params["fileIds"] = fileIds_4.value;
    }
    loading.value = true;
    const res = await confirmDetectorIsolate(params, () => {
      loading.value = false;
    });
    loading.value = false;
    PxMessage.success("确认成功！");
    cancelHandler();
  });
}, delay);

const noticeHandler = useThrottleFn(async () => {
  PxMessageBox.confirm("确定通知解隔离吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const {
      query: { id = "" }
    } = route;
    if (!id) return;
    await noticeReDetectorIsolate(id as string);
    PxMessage.success("解隔离成功！");
    loading.value = true;
    const re = await queryReminderContent({ id }, () => {
      loading.value = false;
    });
    loading.value = false;
    const { notifyContentList = [] } = re;
    if (notifyContentList?.length) {
      const d = notifyContentList.map(item => h("li", { style: { display: "block", marginBottom: "10px", color: "#555" } }, { default: () => item }));
      PxMessageBox({
        title: "注意",
        customStyle: {
          maxWidth: "700px"
        },
        message: h(PxScrollbar, { style: { height: "300px" } }, () => h("ul", null, [...d])),
        callback() {
          cancelHandler();
        }
      });
    } else {
      await nextTick();
      cancelHandler();
    }
  });
}, delay);

const isolateOneTime = (type: 0 | 1 = 0) => {
  isolateDialogType.value = type;
  isolateDialogVisiable.value = true;
};

const isolateSuccessHandler = () => {
  cancelHandler();
};

const init = async () => {
  // status    (1:未隔离 2:隔离已执行 3:隔离已确定 4:解隔离已通知 5:解隔离已执行 6:完成)
  //  待执行：1，4   待确认：2，5   待解隔离通知：3
  const {
    query: { status = "", id = "" }
  } = route;
  if (!id) return;
  const res = await queryDetectorIsolateDetail(id as string);
  if (!res) return;
  detailData.value = res;
  const { fileIdList = [], isolationSubTaskDTO = {}, disisolationSubTaskDTO = {}, reportIds = [] } = res;
  const { fileIdList: fileIdList_2 = [], executeRemark: executeRemark_2 = "" } = isolationSubTaskDTO || {};
  const { fileIdList: fileIdList_3 = [], executeRemark: executeRemark_3 = "" } = disisolationSubTaskDTO || {};
  // 基础信息 文档
  fileList.value = await queryFileListFn(fileIdList);
  // 隔离
  fileList_2.value = await queryFileListFn(fileIdList_2);
  form.executeRemark = executeRemark_2;
  // 解隔离
  fileList_3.value = await queryFileListFn(fileIdList_3);
  form_2.executeRemark = executeRemark_3;
  // 解隔离执行确认（标定）
  fileList_4.value = await queryFileListFn(reportIds);
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <div ref="detectorIsolateRef" v-loading="loading" class="detector-isolate-edit">
    <div class="edit-btn">
      <px-button type="primary" :icon="ArrowLeft" @click="cancelHandler">返回</px-button>
      <div class="right-btns">
        <div v-if="isShowIsolateBtn" class="right-btns-item">
          <!-- <px-button type="primary" :disabled="isolateDisabled" @click="isolateOneTime(0)">一键隔离</px-button>
          <px-button type="info" :disabled="!isolateDisabled" @click="isolateOneTime(1)">一键解隔离</px-button> -->
        </div>
        <div v-if="isShowConfirm" class="right-btns-item">
          <px-button type="primary" plain @click="sendBackHandler">退回</px-button>
          <px-button type="primary" @click="confirmHandler">确认</px-button>
        </div>
        <div v-if="isShowNotive" class="right-btns-item">
          <px-button type="primary" @click="noticeHandler">通知解隔离</px-button>
        </div>
      </div>
    </div>
    <div class="edit-content">
      <div class="content-item">
        <div class="item-title">基础信息</div>
        <baseInfoTable />
      </div>
      <div class="content-item">
        <div class="item-title-inside">文档</div>
        <FileUpload :fileType="uploadType" :fileList="fileList" :countLimit="3" />
      </div>
      <div class="content-item">
        <div class="item-title">隔离清单</div>
        <commonTable
          ref="commonTableRef"
          :pagination="false"
          :tableCloumns="tableCloumns"
          :list="detailData?.detectorChecklistDTOList"
          :max-height="260"
        />
      </div>

      <div v-if="isShowIsolateData" class="content-item">
        <div class="item-title">隔离</div>
        <FileUpload :fileType="uploadType_2" :fileList="fileList_2" :countLimit="3" @changeFileList="changeFileListHandler" />
      </div>
      <div v-if="isShowIsolateData" class="content-item">
        <div class="item-title-inside">备注</div>
        <px-input
          v-model.trim="form.executeRemark"
          :disabled="uploadType_2 === 'view'"
          :rows="2"
          type="textarea"
          status="warning"
          placeholder="请输入备注"
        />
      </div>

      <div v-if="isShowReIsolateData" class="content-item">
        <div class="item-title">解隔离</div>
        <FileUpload :fileType="uploadType_3" :fileList="fileList_3" :countLimit="3" @changeFileList="changeFileListHandler_2" />
      </div>
      <div v-if="isShowReIsolateData" class="content-item">
        <div class="item-title-inside">备注</div>
        <px-input
          v-model.trim="form_2.executeRemark"
          :disabled="uploadType_3 === 'view'"
          :rows="2"
          type="textarea"
          status="warning"
          placeholder="请输入备注"
        />
      </div>

      <div v-if="isShowReIsolateReportData" class="content-item">
        <div class="item-title-inside item-title-inside-validate">上传报告</div>
        <FileUpload :fileType="uploadType_4" :fileList="fileList_4" :countLimit="3" @changeFileList="changeFileListHandler_3" />
      </div>
    </div>
    <ReTeleport v-if="isShowSubmit" submitText="提交" @cancel="cancelHandler" @submit="submitHandler" />
    <isolateDialog
      v-if="isolateDialogVisiable"
      v-model="isolateDialogVisiable"
      :type="isolateDialogType"
      :list="detailData?.detectorChecklistDTOList"
      @success="isolateSuccessHandler"
    />
  </div>
</template>

<style lang="scss" scoped>
.detector-isolate-edit {
  box-sizing: border-box;
  padding: 16px;
  background-color: #fff;

  .edit-btn {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .right-btns {
      display: flex;
      gap: 16px;
      align-items: center;

      .right-btns-item {
        display: flex;
        align-items: center;
      }
    }
  }

  .edit-content {
    .content-item {
      .item-title {
        margin-top: 32px;
        margin-bottom: 20px;
        font-size: 16px;
        font-weight: 600;
        line-height: 1;
        color: #333;
      }

      .item-title-inside {
        padding-left: 6px;
        margin-top: 20px;
        margin-bottom: 20px;
        font-size: 14px;
        font-weight: 600;
        line-height: 1;
        color: #555;
        border-left: 4px solid #3b82f6;
      }

      .item-title-inside-validate::after {
        font-size: 14px;
        color: red;
        vertical-align: top;
        content: " *";
      }
    }
  }
}
</style>
